package com.hnxxxy.oa.system.controller;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.SaTokenInfo;
import cn.dev33.satoken.stp.StpUtil;

import com.hnxxxy.oa.annotation.SysLog;
import com.hnxxxy.oa.enums.BizCodeEnum;
import com.hnxxxy.oa.system.model.SysLoginLogDO;
import com.hnxxxy.oa.system.model.SysUserDO;
import com.hnxxxy.oa.system.constant.UserConstant;
import com.hnxxxy.oa.system.request.GeneralPageRequest;
import com.hnxxxy.oa.system.request.UserLoginRequest;
import com.hnxxxy.oa.system.request.UserPageByUsernameRequest;
import com.hnxxxy.oa.system.request.UserRegisterRequest;
import com.hnxxxy.oa.system.service.SysLoginLogService;
import com.hnxxxy.oa.system.service.SysUserRoleService;
import com.hnxxxy.oa.system.service.SysUserService;
import com.hnxxxy.oa.utils.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author ZHOUSHILIN
 * @data 2022 - 05 - 03 - 15:35
 */
@Api(value = "SysUserController",tags = "用户接口")
@RestController
@RequestMapping("/api/system/v1")
public class SysUserController {

    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysLoginLogService sysLoginLogService;

    @Resource
    private SysUserRoleService sysUserRoleService;

    @ApiOperation(value = "用户注册")
    @PostMapping("/register")
    @SysLog("用户注册")
    public R userRegister(@RequestBody UserRegisterRequest userRegisterRequest){
        if(userRegisterRequest == null){
            return R.buildResult(BizCodeEnum.PARAM_ERROR);
        }
        String username=userRegisterRequest.getUsername();
        String password=userRegisterRequest.getPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String email = userRegisterRequest.getEmail();
        Integer gender = userRegisterRequest.getGender();
        String actualName = userRegisterRequest.getActualName();
        Integer roleId = userRegisterRequest.getRoleId();
        if(StringUtils.isAllBlank(username,password,checkPassword,email,actualName)){
            return R.buildResult(BizCodeEnum.PARAM_NULL);
        }
        if(gender==null || roleId==null){
            return R.buildResult(BizCodeEnum.PARAM_NULL);
        }
        long userId = sysUserService.userRegister(userRegisterRequest);
        return R.buildSuccess(userId);
    }

    @ApiOperation(value = "用户登录")
    @PostMapping("/login")
    public R userLogin(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest request){

        if (userLoginRequest==null){
            return R.buildResult(BizCodeEnum.PARAM_ERROR);
        }
        Exception exception=null;
        String username = userLoginRequest.getUsername();
        String password = userLoginRequest.getPassword();
        if(StringUtils.isAnyBlank(username,password)){
            return R.buildResult(BizCodeEnum.PARAM_NULL);
        }
        SysUserDO sysUser=null;
        try {
            sysUser = sysUserService.userLogin(username, password);
        }catch (Exception e){
            exception=e;
        }
        if (sysUser==null){
            insertFailLoginLog(request,exception);
            return R.buildError(exception.getMessage());
        }else{
            //sa-token登录
            StpUtil.login(sysUser.getId());
            //获取token
            SaTokenInfo tokenInfo = StpUtil.getTokenInfo();
            //获取session
            SaSession session = StpUtil.getSession();
            //设置用户信息
            session.set(UserConstant.SESSION_USER_KEY,sysUser);
            //插入登录成功的登录日志
            insertSuccessLoginLog(sysUser,request);
            return R.buildSuccess(tokenInfo);
        }
    }

    @PostMapping("/logout")
    @ApiOperation(value = "用户登出")
    @SysLog("用户登出")
    public R userLogout(){
        SaSession session = StpUtil.getSession();
        SysUserDO sysUserDO= (SysUserDO)session.get(UserConstant.SESSION_USER_KEY);
        session.delete(UserConstant.SESSION_USER_KEY);
        StpUtil.logout(sysUserDO.getId());
        return R.buildSuccess(sysUserDO.getId());
    }

    @PostMapping("/deleteUser")
    @ApiOperation(value = "用户删除")
    @SysLog("用户删除")
    public R deleteUser(@RequestBody Integer id){
        if (id<=0){
            return R.buildResult(BizCodeEnum.PARAM_ERROR);
        }
        //删除用户
        boolean b = sysUserService.deleteUser(id);

        //删除该用户的用户角色
        sysUserRoleService.deleteUserRole(id,null);
        return R.buildSuccess(b);
    }

    @PostMapping("/deleteUserByBatch")
    @ApiOperation(value = "用户批量删除")
    @SysLog("用户删除")
    public R deleteUserByBatch(@RequestBody String ids){
        if (ids==null){
            return R.buildResult(BizCodeEnum.PARAM_ERROR);
        }
        System.out.println(ids);
        //删除用户
        boolean b = sysUserService.deleteUserByBatch(ids);

        String substring = ids.substring(1, ids.length() - 1);
        String[] split = substring.split(",");
        for (int i=0;i<split.length;i++){
            //删除该用户的用户角色
            sysUserRoleService.deleteUserRole(Integer.parseInt(split[i]),null);
        }
        return R.buildSuccess(b);
    }


    @PostMapping("pageListUser")
    @ApiOperation(value = "分页展示所有用户")
    @SysLog("分页展示所有用户数据")
    public R pageListUsers(@RequestBody UserPageByUsernameRequest userPageByUsernameRequest){
        if (userPageByUsernameRequest==null){
            return R.buildResult(BizCodeEnum.PARAM_ERROR);
        }
        Map<String, Object> stringObjectMap = sysUserService.pageListUsers(userPageByUsernameRequest);
        return R.buildSuccess(stringObjectMap);
    }

    /**
     * 插入登录成功日志
     * @param sysUser
     * @param request
     */
    private void insertSuccessLoginLog(SysUserDO sysUser,HttpServletRequest request){
        SysLoginLogDO sysLoginLogDO = new SysLoginLogDO();
        sysLoginLogDO.setUserId(sysUser.getId());
        sysLoginLogDO.setUsername(sysUser.getUsername());
        sysLoginLogDO.setIsSuccess(1);
        sysLoginLogDO.setIp(sysLoginLogService.getIpAddr(request));
        sysLoginLogDO.setMessage(StpUtil.getTokenInfo().getTokenValue());
        sysLoginLogService.insert(sysLoginLogDO);
    }

    /**
     * 插入登录失败日志
     * @param request
     * @param e
     */
    private void insertFailLoginLog(HttpServletRequest request,Exception e){
        SysLoginLogDO sysLoginLogDO = new SysLoginLogDO();
        sysLoginLogDO.setIsSuccess(0);
        sysLoginLogDO.setIp(sysLoginLogService.getIpAddr(request));
        sysLoginLogDO.setRemark(e.getMessage());
        sysLoginLogDO.setMessage(e.getMessage());
        sysLoginLogService.insert(sysLoginLogDO);
    }

}